package com.jack.xmlparser.ui;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import com.jack.xmlparser.R;
import com.jack.xmlparser.iui.BaseParser;
import com.jack.xmlparser.parser.DomParserForBook;
import com.jack.xmlparser.parser.PullParserForBook;
import com.jack.xmlparser.parser.SaxParserForBook;
import com.jack.xmlparser.util.Book;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	private TextView mText;
	private Button mObjectBtn;
	private Button mXmlBtn;
	private List<Object> mBooks;
	private BaseParser mBookParser;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mText = (TextView) findViewById(R.id.text);
		mObjectBtn = (Button) findViewById(R.id.parser_to_object);
		mXmlBtn = (Button) findViewById(R.id.parser_to_xml);
		
		mObjectBtn.setOnClickListener(this);
		mXmlBtn.setOnClickListener(this);	
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		try {
			if (v.getId() == R.id.parser_to_object) {
				InputStream is = getAssets().open("books.xml");
//				mBookParser = new SaxParserForBook();
//				mBookParser = new DomParserForBook();
				mBookParser = new PullParserForBook();
				mBooks = mBookParser.parserToObject(is);
				for (Object o : mBooks) {
					if (o instanceof Book) {
						Book book = (Book) o;
						Log.e("JackHan", "" + book.getId() + " " + book.getName() + " " + book.getPrice());
					}
				}
			} else if (v.getId() == R.id.parser_to_xml) {
				String  xml = mBookParser.parserToXml(mBooks);
				mText.setText(xml);
				if (xml != null && !xml.equals("")) {
					FileOutputStream fos = openFileOutput("test.xml", MODE_PRIVATE);
					fos.write(xml.getBytes("utf-8"));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
}
